//
//  Button-Style.swift
//  jocool
//
//  Created by tong on 16/7/6.
//  Copyright © 2016年 zhuxietong. All rights reserved.
//

import UIKit




extension UIButton{
    
    
    final public var ui:ButtonStyle{
        set{
            newValue.owner = self
            self.__style.setObject(newValue, forKey: "ui" as NSCopying)
        }
        get{
            if let st = self.__style.object(forKey: "ui") as? ButtonStyle
            {
                st.owner = self
                return st
            }
            else
            {
                let style = ButtonStyle()
                style.owner = self
                self.__style.setObject(style, forKey: "ui" as NSCopying)
                return style
            }
        }
    }
    
}



extension UIColor{
    public var _light:UIColor{
        get{
            if #available(iOS 13.0, *) {
                return self.resolvedColor(with: UITraitCollection(userInterfaceStyle: .light))
            }
            return self
        }
    }
    public var _dark:UIColor{
        get{
            if #available(iOS 13.0, *) {
                let d = self.resolvedColor(with: UITraitCollection(userInterfaceStyle: .dark))
                return d
            }
            return self
        }
    }
    
    public var invert:UIColor{
        get{
            var lfromRed: CGFloat = 0
            var lfromGreen: CGFloat = 0
            var lfromBlue: CGFloat = 0
            var lfromAlpha: CGFloat = 0
            self.getRed(&lfromRed, green: &lfromGreen, blue: &lfromBlue, alpha: &lfromAlpha)
            lfromRed = 1.0 - lfromRed
            lfromGreen = 1.0 - lfromBlue
            lfromBlue = 1.0 - lfromBlue
            return UIColor(red: lfromRed, green: lfromGreen, blue: lfromBlue, alpha: lfromAlpha)
          
        }
    }
    
    public var highlightedColor:UIColor{
        get{
            if #available(iOS 13.0, *) {
                let l = self.resolvedColor(with: UITraitCollection(userInterfaceStyle: .light))
                let d = self.resolvedColor(with: UITraitCollection(userInterfaceStyle: .dark))
                
                var lfromRed: CGFloat = 0
                var lfromGreen: CGFloat = 0
                var lfromBlue: CGFloat = 0
                var lfromAlpha: CGFloat = 0
                l.getRed(&lfromRed, green: &lfromGreen, blue: &lfromBlue, alpha: &lfromAlpha)
              
              
                lfromRed = lfromRed * 0.7
                lfromGreen = lfromGreen * 0.7
                lfromBlue = lfromBlue * 0.7
                lfromAlpha = lfromAlpha * 0.7

                if lfromAlpha == 0{
                    lfromAlpha = 0.1
                }
              
                let l_color = UIColor(red: lfromRed, green: lfromGreen, blue: lfromBlue, alpha: lfromAlpha)
                
                var dfromRed: CGFloat = 0
                var dfromGreen: CGFloat = 0
                var dfromBlue: CGFloat = 0
                var dfromAlpha: CGFloat = 0
                d.getRed(&dfromRed, green: &dfromGreen, blue: &dfromBlue, alpha: &dfromAlpha)
             
                dfromRed = dfromRed * 1.5
                dfromGreen = dfromGreen * 1.5
                dfromBlue = dfromBlue * 1.5
                dfromAlpha = dfromAlpha * 0.2

                if dfromAlpha == 0{
                    dfromAlpha = 0.1
                }
             
                let d_color = UIColor(red: dfromRed, green: dfromGreen, blue: dfromBlue, alpha: dfromAlpha)
                return UIColor.color(lColor: l_color, dColor: d_color)
                
            } else {
                return self
                          // Fallback on earlier versions
            }
        }
    }
    
    public var maskColor:UIColor{
        get{
            if #available(iOS 13.0, *) {
                let l = self.resolvedColor(with: UITraitCollection(userInterfaceStyle: .light))
                let d = self.resolvedColor(with: UITraitCollection(userInterfaceStyle: .dark))
                var lfromRed: CGFloat = 0
                var lfromGreen: CGFloat = 0
                var lfromBlue: CGFloat = 0
                var lfromAlpha: CGFloat = 0
                l.getRed(&lfromRed, green: &lfromGreen, blue: &lfromBlue, alpha: &lfromAlpha)
              
              
                lfromRed = lfromRed * 0.8
                lfromGreen = lfromGreen * 0.8
                lfromBlue = lfromBlue * 0.8
                lfromAlpha = lfromAlpha * 0.4

                if lfromAlpha == 0{
                    lfromAlpha = 0.1
                }
              
                let l_color = UIColor(red: lfromRed, green: lfromGreen, blue: lfromBlue, alpha: lfromAlpha)
                
                var dfromRed: CGFloat = 0
                var dfromGreen: CGFloat = 0
                var dfromBlue: CGFloat = 0
                var dfromAlpha: CGFloat = 0
                d.getRed(&dfromRed, green: &dfromGreen, blue: &dfromBlue, alpha: &dfromAlpha)
             
                dfromRed = dfromRed * 3
                dfromGreen = dfromGreen * 3
                dfromBlue = dfromBlue * 3
                dfromAlpha = dfromAlpha * 1

                if dfromRed < 0.1{
                    dfromRed = 0.26
                }
                if dfromGreen < 0.1{
                    dfromGreen = 0.26
                }
                if dfromBlue < 0.1{
                    dfromBlue = 0.26
                }
                if dfromAlpha == 0{
                    dfromAlpha = 0.1
                }
             
                let d_color = UIColor(red: dfromRed, green: dfromGreen, blue: dfromBlue, alpha: dfromAlpha)
                return UIColor.color(lColor: l_color, dColor: d_color)
                
            } else {
                return self
                          // Fallback on earlier versions
            }
        }
    }
}
extension UIButton
{
    public var __buttonColor: UIColor {
        set(newValue) {
            
//            if #available(iOS 13.0, *) {
//                let l = newValue.resolvedColor(with: UITraitCollection(userInterfaceStyle: .light))
//                let d = newValue.resolvedColor(with: UITraitCollection(userInterfaceStyle: .dark))
//            } else {
//                // Fallback on earlier versions
//            }
//
//            var fromRed: CGFloat = 0
//            var fromGreen: CGFloat = 0
//            var fromBlue: CGFloat = 0
//            var fromAlpha: CGFloat = 0
//            newValue.getRed(&fromRed, green: &fromGreen, blue: &fromBlue, alpha: &fromAlpha)
//
//
//            fromRed = fromRed * 0.7
//            fromGreen = fromGreen * 0.7
//            fromBlue = fromBlue * 0.7
//            fromAlpha = fromAlpha * 0.7
//
//            if fromAlpha == 0{
//                fromAlpha = 0.1
//            }
//            let h_color = UIColor(red: fromRed, green: fromGreen, blue: fromBlue, alpha: fromAlpha)
            
            self.setBackgroundImage(UIImage.dynamic(color: newValue), for: .normal)
//            self.setBackgroundImage(UIImage.dynamic(color: newValue.maskColor), for: .highlighted)
            
            self.layer.borderColor = newValue.cgColor
        }
        get {
            return UIColor(cgColor: self.layer.borderColor!)
        }
    }

}

extension UIButton{
    private struct __ButtonStyle {
        static var actionID = "ButtonStyleActionID"
    }
    
    public var actionID: String {
        get {
            if let ID = objc_getAssociatedObject(self, &__ButtonStyle.actionID) as? String
            {
                return ID
            }
            return ""            
        }
        set {
            objc_setAssociatedObject(self,  &__ButtonStyle.actionID, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}







public class ButtonStyle:BaseStyle<UIButton> {
    
    public enum ImagePosition{
        case left
        case right
    }
    
    

    var scolor:UIColor?
    var ncolor:UIColor?
    var ntitle:String?
    var stitle:String?
    
    var simage:UIImage?
    var nimage:UIImage?
    
    var padding:UIEdgeInsets?

    var imgPosition:ImagePosition = .left
    
    var font:UIFont?
    var buttonColor:UIColor?
    
    public var actionID:String?
    public typealias ButtonAction = ()-> Void

    
    var touchUpInsideAction:ButtonAction? = nil
    
    @objc func _touchUpInsideAction() {
        if let aciton = self.touchUpInsideAction{
            aciton()
        }
    }
    
    
    public override init() {
    }
    
    @discardableResult
    public override func assign(to owner:UIButton) -> ButtonStyle {
//        self.owner = owner
        owner.ui = self
        self.run()
        return self
    }
    
    func setToucUpInSide(for button:UIButton?) {
        if let o = button{
            if(o.__extention["ui_touchUpInside","NO"] == "NO"){
                owner?.addTarget(self, action: #selector(_touchUpInsideAction), for: .touchUpInside)
                o.__extention["ui_touchUpInside"] = "YES"
            }
        }
    }
    
    
    @discardableResult
    public func touchUpInside(_ action:@escaping ButtonAction) ->ButtonStyle{
        self.touchUpInsideAction = action
        setToucUpInSide(for: owner)
        return self
    }
    
    

    @discardableResult
    public class func new() ->ButtonStyle{
        
        return ButtonStyle()
    }

    @discardableResult
    public func actionID(ID:String) ->ButtonStyle{
        self.actionID = ID
        self.owner?.actionID = ID
        return self
    }
    
    @discardableResult
    public func buttonColor(hex:String) ->ButtonStyle
    {
        
        self.buttonColor = UIColor(shex: hex)
        self.owner?.__buttonColor = self.buttonColor!
        return self
    }
    
    @discardableResult
    public func buttonColor(color:UIColor) ->ButtonStyle
    {
        self.buttonColor = color
        self.owner?.__buttonColor = self.buttonColor!
        return self
    }
    
    
    @discardableResult
    public func ncolor(hex:String) ->ButtonStyle
    {
        self.ncolor =  UIColor(shex: hex)
        self.owner?.setTitleColor(self.ncolor!, for: .normal)
        return self
    }
    @discardableResult
    public func scolor(hex:String) ->ButtonStyle
    {
        self.scolor = UIColor(shex: hex)
        self.owner?.setTitleColor(self.scolor, for: .selected)
        return self
    }

   
    @discardableResult
    public func ncolor(color:UIColor) ->ButtonStyle
    {
        self.ncolor = color
        self.owner?.setTitleColor(color, for: .normal)
        return self
    }
    
    @discardableResult
    public func scolor(color:UIColor) ->ButtonStyle
    {
        self.scolor = color
        self.owner?.setTitleColor(color, for: .selected)
        return self
    }
    @discardableResult
    public func ntitle(title:String) ->ButtonStyle
    {
        self.ntitle = title
        self.owner?.setTitle(title, for: .normal)
        return self
    }
    @discardableResult
    public func stitle(title:String) ->ButtonStyle
    {
        self.stitle = title
        self.owner?.setTitle(title, for: .selected)
        return self
    }
    
    @discardableResult
    public func font(font:UIFont) -> ButtonStyle{
        self.font = font
        self.owner?.titleLabel?.font = self.font!
        return self
    }

    @discardableResult
    public func font(size:CGFloat) -> ButtonStyle{
        self.font = UIFont.systemFont(ofSize: size.fs)
        self.owner?.titleLabel?.font = self.font!
        return self
    }
    @discardableResult
    public func bfont(size:CGFloat) -> ButtonStyle{
        self.font = UIFont.boldSystemFont(ofSize: size.fs)
        self.owner?.titleLabel?.font = self.font!
        return self
    }
    
    @discardableResult
    public func imagePosition(_ position:ImagePosition) -> ButtonStyle{
        self.imgPosition = position
        
        switch imgPosition {
        case .right:
            let interval:CGFloat = 3
            
//            CGSize size =[content sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}];
            let title = self.owner?.title(for: .normal) ?? ""
            let font = self.owner?.titleLabel?.font ?? UIFont.systemFont(ofSize: 13.fs)
            

            
            let titleSize = NSString(string: title).size(withAttributes: [NSAttributedString.Key.font:font])
            let imageSize = self.owner?.image(for: .normal)?.size ?? .zero

//            let oss = UIEdgeInsetsMake(0,titleSize.width + interval, 0, -(titleSize.width + interval));
            self.owner?.imageEdgeInsets = UIEdgeInsets(top: 0,left: titleSize.width + interval, bottom: 0, right: -(titleSize.width + interval));
            self.owner?.titleEdgeInsets = UIEdgeInsets(top: 0, left: -(imageSize.width + interval), bottom: 0, right: imageSize.width + interval);
//            run()
        default:
            break
        }
       
        return self
    }
    
    @discardableResult
    public func simage(_ image:UIImage?) -> ButtonStyle{
        self.simage = image
        self.owner?.setImage(image, for: .selected)
      
        return self
    }
    
    @discardableResult
    public func nimage(_ image:UIImage?) -> ButtonStyle{
        if self.simage == nil
        {
            self.simage(nimage)
        }
        self.nimage = image
        self.owner?.setImage(image, for: .normal)
        return self
    }
    
    @discardableResult
    public func padding(insets:UIEdgeInsets?) -> ButtonStyle{
        self.padding = insets
        if let pd = self.padding{
            self.owner?.contentEdgeInsets = pd
        }
        return self
    }
    
    
    @discardableResult
    public func hidden(hidden:Bool) -> ButtonStyle{
        self.isHidden = hidden
        self.owner?.isHidden = self.isHidden
        return self
    }

    
    
    public override func run() {
        

        self.owner?.actionID = self.actionID ?? ""
        if let sc = self.scolor
        {
            self.scolor(color: sc)
        }
        if let nc = self.ncolor
        {
            self.ncolor(color: nc)
        }
        if let nt = self.ntitle
        {
            self.ntitle(title: nt)
        }
        if let st = self.stitle
        {
            self.ntitle(title: st)
        }
        if let f = self.font
        {
            self.owner?.titleLabel?.font = f
        }
        if let bc = self.buttonColor
        {
            self.buttonColor(color: bc)
        }
        
        if let nimg = self.nimage{
            self.nimage(nimg)
        }
        if let simg = self.simage{
            self.simage(simg)
        }
        if let pd = self.padding
        {
            self.padding(insets: pd)
        }
        
        switch imgPosition {
        case .right:
            let interval:CGFloat = 3
            
            //            CGSize size =[content sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}];
            let title = self.owner?.title(for: .normal) ?? ""
            let font = self.owner?.titleLabel?.font ?? UIFont.systemFont(ofSize: 13)
            
            
            
            let titleSize = NSString(string: title).size(withAttributes: [NSAttributedString.Key.font:font])
            let imageSize = self.owner?.image(for: .normal)?.size ?? .zero
            
            //            let oss = UIEdgeInsetsMake(0,titleSize.width + interval, 0, -(titleSize.width + interval));
            self.owner?.imageEdgeInsets = UIEdgeInsets(top: 0,left: titleSize.width + interval, bottom: 0, right: -(titleSize.width + interval));
            self.owner?.titleEdgeInsets = UIEdgeInsets(top: 0, left: -(imageSize.width + interval), bottom: 0, right: imageSize.width + interval);

        default:
            break
        }
        setToucUpInSide(for: owner)
        
        super.run()


        
    }
    
    
    
}


